module ActiveRecord #:nodoc:
  class Base
    @@bc_logger ||= Logger.new("#{RAILS_ROOT}/log/brokencompass.log")

    #Initializing index container if not already initialized
    @@broken_compass_index ||= {}

    #Loading configurations from config/brokencompass.yml
    bc_config = nil
    config_file_path = File.join("vendor","plugins","broken_compass","config","brokencompass.yml")
    if File.exist?(config_file_path)
      bc_config = YAML::load(File.open(config_file_path))
    end
    bc_config ||= {}

    #Assigns load_index_on_application_start, default to false
    bc_config["load_index_on_application_start"] ||= false

    #Loads all available indexes, depending upon flagset position
    if bc_config["load_index_on_application_start"]
      #Loading index from file one by one
      Dir["broken_compass/*"].each do |dir_item|
        if dir_item.to_s.split(".").last == "index"
          puts "Loading index... [#{dir_item}]"
          begin
             #Loading from index file
             model_symbol  = dir_item.to_s.split("/").last.split(".").first.to_sym
             File.open(dir_item) { |f| @@broken_compass_index[model_symbol] = Marshal.load(f) }
          rescue
            puts "Error occurred while loading index from #{index_file_with_path}.\n Please redo #{index_file}"
            return
          end
        end
      end

    end

  end
end
